package com.beauty.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.beauty.payment.config.AlipayConfig;
import com.beauty.payment.dto.AlipayOrderRequest;
import com.beauty.payment.result.Result;
import com.beauty.payment.service.PaymentService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/payment")
@RequiredArgsConstructor
@Slf4j
public class AlipayController {

    private final AlipayClient alipayClient;
    private final AlipayConfig alipayConfig;
    private final PaymentService paymentService;

    /**
     * 创建支付宝支付订单
     */
    @PostMapping("/alipay/create")
    public Result<String> createAlipayOrder(@RequestBody AlipayOrderRequest request) {
        log.info("【支付服务】接收到创建支付宝订单请求: {}", request);
        
        // 构建支付请求
        try {
            // 创建支付请求
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            
            // 设置异步通知地址 - 通知支付结果
            alipayRequest.setNotifyUrl(alipayConfig.getNotifyUrl());
            
            // 设置同步返回地址 - 支付完成后跳转
            alipayRequest.setReturnUrl(request.getReturnUrl() != null ? 
                    request.getReturnUrl() : alipayConfig.getReturnUrl());
            
            // 准备请求参数
            Map<String, Object> bizContent = new HashMap<>();
            bizContent.put("out_trade_no", request.getOrderNumber());
            bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
            bizContent.put("total_amount", request.getTotalAmount().toString());
            bizContent.put("subject", request.getSubject());
            
            if (request.getBody() != null && !request.getBody().isEmpty()) {
                bizContent.put("body", request.getBody());
            }
            
            alipayRequest.setBizContent(com.alibaba.fastjson.JSON.toJSONString(bizContent));
            
            // 发送请求
            String form = alipayClient.pageExecute(alipayRequest).getBody();
            
            // 记录支付请求
            paymentService.recordPaymentRequest(request.getOrderNumber(), request.getTotalAmount(), "ALIPAY");
            
            log.info("【支付服务】支付宝表单生成成功");
            return Result.success(form);
        } catch (AlipayApiException e) {
            log.error("【支付服务】创建支付宝订单异常", e);
            return Result.error("创建支付宝订单失败: " + e.getMessage());
        }
    }
    
    /**
     * 支付宝支付结果异步通知
     */
    @PostMapping("/alipay/notify")
    public String alipayNotify(HttpServletRequest request) {
        log.info("【支付服务】接收到支付宝异步通知");
        
        // 获取支付宝POST过来的反馈信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            StringBuilder valueStr = new StringBuilder();
            for (int i = 0; i < values.length; i++) {
                valueStr.append((i == values.length - 1) ? values[i] : values[i] + ",");
            }
            params.put(name, valueStr.toString());
        }
        
        log.info("【支付服务】支付宝异步通知参数: {}", params);
        
        // 处理通知
        try {
            // 验证签名
            boolean signVerified = paymentService.verifyAlipaySign(params);
            if (signVerified) {
                // 验证通过，处理订单
                String orderNumber = params.get("out_trade_no");
                String tradeStatus = params.get("trade_status");
                String tradeNo = params.get("trade_no");
                String totalAmount = params.get("total_amount");
                
                // 支付成功
                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                    log.info("【支付服务】订单{}支付成功，支付宝交易号: {}", orderNumber, tradeNo);
                    paymentService.handlePaymentSuccess(
                            orderNumber, 
                            tradeNo, 
                            new BigDecimal(totalAmount),
                            "ALIPAY");
                    return "success";
                }
            } else {
                log.error("【支付服务】支付宝异步通知验签失败");
            }
        } catch (Exception e) {
            log.error("【支付服务】处理支付宝异步通知异常", e);
        }
        
        return "fail";
    }
    
    /**
     * 支付宝支付结果同步通知
     */
    @GetMapping("/alipay/return")
    public Result<Map<String, Object>> alipayReturn(HttpServletRequest request) {
        log.info("【支付服务】接收到支付宝同步通知");
        
        // 获取支付宝GET过来的反馈信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            StringBuilder valueStr = new StringBuilder();
            for (int i = 0; i < values.length; i++) {
                valueStr.append((i == values.length - 1) ? values[i] : values[i] + ",");
            }
            params.put(name, valueStr.toString());
        }
        
        log.info("【支付服务】支付宝同步通知参数: {}", params);
        
        // 验证签名
        try {
            boolean signVerified = paymentService.verifyAlipaySign(params);
            if (signVerified) {
                String orderNumber = params.get("out_trade_no");
                String tradeNo = params.get("trade_no");
                
                // 返回结果
                Map<String, Object> result = new HashMap<>();
                result.put("orderNumber", orderNumber);
                result.put("tradeNo", tradeNo);
                result.put("success", true);
                
                log.info("【支付服务】同步通知验签成功，订单号: {}, 支付宝交易号: {}", orderNumber, tradeNo);
                return Result.success(result);
            } else {
                log.error("【支付服务】支付宝同步通知验签失败");
                return Result.error("支付结果验证失败");
            }
        } catch (Exception e) {
            log.error("【支付服务】处理支付宝同步通知异常", e);
            return Result.error("处理支付结果异常: " + e.getMessage());
        }
    }
    
    /**
     * 查询支付状态
     */
    @GetMapping("/status/{orderNumber}")
    public Result<Map<String, Object>> checkPaymentStatus(@PathVariable String orderNumber) {
        log.info("【支付服务】接收到查询支付状态请求，订单号: {}", orderNumber);
        
        try {
            // 先查询本地支付记录
            boolean isPaid = paymentService.isOrderPaid(orderNumber);
            
            // 如果本地记录已支付，直接返回
            if (isPaid) {
                Map<String, Object> result = new HashMap<>();
                result.put("orderNumber", orderNumber);
                result.put("paid", true);
                return Result.success(result);
            }
            
            // 若本地未记录支付成功，则查询支付宝交易状态
            AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
            
            Map<String, Object> bizContent = new HashMap<>();
            bizContent.put("out_trade_no", orderNumber);
            
            alipayRequest.setBizContent(com.alibaba.fastjson.JSON.toJSONString(bizContent));
            
            AlipayTradeQueryResponse response = alipayClient.execute(alipayRequest);
            
            Map<String, Object> result = new HashMap<>();
            result.put("orderNumber", orderNumber);
            
            if (response.isSuccess()) {
                String tradeStatus = response.getTradeStatus();
                result.put("tradeStatus", tradeStatus);
                
                // 交易成功或交易结束
                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                    // 更新本地支付记录
                    paymentService.handlePaymentSuccess(
                            orderNumber, 
                            response.getTradeNo(), 
                            new BigDecimal(response.getTotalAmount()),
                            "ALIPAY");
                    result.put("paid", true);
                } else {
                    result.put("paid", false);
                }
            } else {
                log.error("【支付服务】查询支付宝交易状态失败: {}, {}", response.getCode(), response.getMsg());
                result.put("paid", false);
                result.put("message", "查询交易状态失败");
            }
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("【支付服务】查询支付状态异常", e);
            return Result.error("查询支付状态异常: " + e.getMessage());
        }
    }
    
    /**
     * 关闭支付订单
     */
    @PostMapping("/close/{orderNumber}")
    public Result<Void> closePayment(@PathVariable String orderNumber) {
        log.info("【支付服务】接收到关闭支付订单请求，订单号: {}", orderNumber);
        
        try {
            boolean success = paymentService.closePayment(orderNumber);
            if (success) {
                return Result.success();
            } else {
                return Result.error("关闭支付订单失败");
            }
        } catch (Exception e) {
            log.error("【支付服务】关闭支付订单异常", e);
            return Result.error("关闭支付订单异常: " + e.getMessage());
        }
    }
} 